
//全局对象
var seniorQueryUtil = new SeniorQueryUtil();
var seInfo = function(){
	var id;
	var name;
};
	
function SeniorQueryUtil() {
	this.addSeniorQuery = function(table_wrapperId){
		var inputdiv = jQuery('#'+table_wrapperId+' .dataTables_filter').find("div");
		var seidiv = $('<div style="float:right;padding:8px 0px 0px 8px;"> <a href="javascript:seniorqueryopen();">高级查询</a></div>');
        seidiv.insertBefore(inputdiv);
        jQuery('#'+table_wrapperId+' .col-md-10').removeClass("col-md-10").addClass("col-md-8");
        jQuery('#'+table_wrapperId+' .col-md-2').removeClass("col-md-2").addClass("col-md-4");	
	
	};
    /**
	 * initValue 初始默认值 cmchen 2018.05.29
     * @param id
     * @param url
     * @param nomatches
     * @param isMultiple
     * @param initValue
     */
	this.initRemoteselect2 = function(id,url,nomatches,isMultiple,initValue) {
		$("#"+id).select2({
	        minimumInputLength: 0,
	        multiple: typeof(isMultiple) == 'undefined'?  true : isMultiple,
	        allowClear: true,  //是否允许用户清除文本信息
	        ajax: { 
	            url: url,
	            dataType: 'json',
	            type: "POST",
	            data: function (term, iPage) {
		            if(typeof(beforeAjax) == 'function'){
		            	return beforeAjax(term, iPage);
		            }else{
			            return {
		                    queryParam: term, 
		                    limit: 10,
		                    start: (iPage-1) * 10,
		            	};
		            };
	            },
                processResults: function (data, page) {
	            	if(data.iTotalRecords == undefined){
	            		var more = (page*10)<data.TOTALCOUNT;    //用来判断是否还有更多数据可以加载  
		                return {  
		                	results:data.ROOT,more:more      
		                };
	            	}else{
	            		var more = (page*10)<data.iTotalRecords;    //用来判断是否还有更多数据可以加载  
		                return {  
		                	results:data.aaData,more:more      
		                }; 
	            	}
	            }
	        },
            /*initSelection : function (element, callback) {
				if(initValue != undefined && initValue.length != 0 ){
                    callback(initValue);
				}

            },*/
            templateResult: function(data) {
	        	if(data.number != undefined && data.number != null){
					if(data.itemasstattrname != undefined 
		        		&& data.itemasstattrname != null && data.itemasstattrname != ""){
		        		return  data.number+" "+data.name+"【"+data.itemasstattrname +"】";//注意此处的name，要和ajax返回数组的键值一样 
		        	}	        	
	        		return  data.number+" "+data.name;//注意此处的name，要和ajax返回数组的键值一样 
	        	}
	        	return  data.name;//注意此处的name，要和ajax返回数组的键值一样 
	    	},
            templateSelection: function(data) {
	        	if(data.itemasstattrname != undefined 
	        		&& data.itemasstattrname != null && data.itemasstattrname != ""){
	        		return  data.name+"【"+data.itemasstattrname +"】"
	        			+'<input type="hidden" name ="'+data.name+'" id="'+data.id+'" />';
	        	}
				return  data.name+'<input type="hidden" name ="'+data.name+'" id="'+data.id+'" />';
	   		},
		    formatNoMatches: function(item) {  
		        return  nomatches;
		    }/*,
	        dropdownCssClass: "bigdrop",
	           escapeMarkup: function (m) {
	               return m;
	           } */
    	});
	};
	
	this.initLocalselect2 = function(id,nomatches,localdata) {
		$('#'+id).select2({
		    minimumInputLength   : 0,
		    multiple             : true,
		    createSearchChoice   : function(term, data) {           // 创建搜索结果（使用户可以输入匹配值以外的其它值）
		        return { id: term, name: term };
		    },
		    allowClear: true,  //是否允许用户清除文本信息
            templateSelection : function (item)
		    { return item.name +'<input type="hidden" name ="'+item.name+'" id="'+item.id+'" />'; },  // 选择结果中的显示
            templateResult    : function (item) { return item.name; },  // 搜索列表中的显示
		    data: {
		        results: localdata
		    },
		    formatNoMatches: function(item) {  
		        return  nomatches;
		    },
		});
	};
	

	
	this.getSelect2Input= function(id) {
		var seinfo;
		var se = [];
		se.push($("#"+id).val());
		var selist = [];
		$("#s2id_"+id+" .select2-search-choice").find("input").each(function (){
			seinfo =  new seInfo();
			seinfo.id = $(this).attr("id");
			seinfo.name = $(this).attr("name");
			selist.push(seinfo);
		});		
		se.push(selist);
		return se;
	};
	
	this.checkHasSeniorinfo = function(info) {
		var hasProp = false;  
	    for (var prop in info){  
	        hasProp = true;  
	        break;  
	    } 
	    return hasProp;
	};
	
	this.addSelectedChoice = function(id,sevalue) {
		if(sevalue != undefined && sevalue.length>0){
			for(var i=0;i<sevalue.length;i++){
				var itemasstattrname = sevalue[i].itemasstattrname;
				if(itemasstattrname != undefined && itemasstattrname != null && itemasstattrname != ""){
	        		$("#"+id).data("select2").addSelectedChoice({id : sevalue[i].id,name : sevalue[i].name+"【"+itemasstattrname+"】"});
	        	}else{
	        		$("#"+id).data("select2").addSelectedChoice({id : sevalue[i].id,name : sevalue[i].name});
	        	}
			}
			$($("#s2id_"+id+" .select2-search-field").find("input")).removeClass("select2-default").css("width","22px");
		}	
	};


	this.manageCustomer = function () {
		var seinorid = "";
		var seinorurl = "",isHandledGroupTable = false;
		var selectCustomerTable = function() {
			if(!jQuery().dataTable){
				return ;
			}
	        // begin  table
	        $('#'+seinorid).dataTable({
	            "bProcessing": true,                     //加载数据时显示正在加载信息  
	            "bServerSide": true,                     //指定从服务器端获取数据  
	            "sAjaxSource": seinorurl,//获取数据的url  
	            "fnServerData": retrieveCusData,           //获取数据的处理函数  
	            "fnExtendComp": extendTableFilter,
	            "bAutoWidth": true,                    //自适应宽度
	            "bFilter" : true,                       // 搜索栏
	            "ajax" : "load",
	            "fnQueryTip" : "请输入渠道名称/编码",
	            "aoColumns" : [
	             {
	        		"mData" : null,
	        		"sTitle" : null,
	        		'bSortable': false,
	        		"sDefaultContent" : "",
	            	"mRender" : function(data, type, row) {
	            		var rowJsonStr=JSON.stringify(row);
	        			return "<div class='checker'><span>" +
	        					"<input type='checkbox'  class='checkboxes' id='selectedData' value='1'/>"+
	        					"</span></div><input type='hidden' name='row-data' value="+rowJsonStr+" />";
	        		}   
	        	},{
	        		"mData" : 'number',
	        		"sTitle" : "渠道编码",
	        		"bSortable" : true
	        	},{
	        		"mData" : 'name',
	        		"sTitle" : "渠道名称",
	        		"bSortable" : true,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='name'>"+data+"</span>";
	        		}  
	        	},{
	        		"mData" : 'id',    
	        		"sTitle" : "渠道内码",
	        		"sClass":"hideColumn",
	        		"bSortable" : false,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='id'>"+data+"</span>";
	        		}  
	        	}
	        	],
	           
	        });
	        jQuery('#'+seinorid+'_wrapper .dataTables_filter input').addClass("form-control"); // modify table search input
			
	        jQuery('#'+seinorid+' .group-checkable').change(function (event) {
	            var set = jQuery(this).attr("data-set");
	            var checked = jQuery(this).is(":checked");
	            $(this).closest('span').toggleClass("checked");
	           	jQuery(set).each(function () {
	                if (checked) {
	                    $(this).attr("checked", true);
	                    $(this).closest('span').addClass("checked");
	                    $(this).closest('tr').addClass("active");
	                } else {
	                    $(this).attr("checked", false);
	                    $(this).closest('span').removeClass("checked");
	                    $(this).closest('tr').removeClass("active");
	                }
	            });
	            jQuery.uniform.update(set);
	        });
	        
	        //单击事件监听
	        $('#'+seinorid+' tbody tr').live('click', function () {
	        	var nTds = $('td', this);
	        	var set = nTds[0].children[0].children[0].children[0];
	        	var checked = $(set).is(":checked");
	        	$('span', this).toggleClass("checked");
	        	$(this).toggleClass("active");
	        	$(set).attr("checked", !checked);
	    	});
	        // 处理关于点击Input 第一列选中框，再次触发单击事件的情况
	    	$("#"+seinorid+" tbody tr input").live('click', function(e){
	    		var checked = $(this).is(":checked");
	    		$(this).closest('span').toggleClass("checked");
	    		$(this).closest('tr').toggleClass("active");
		    	e.stopPropagation();
	    	});
		};
	
		var extendTableFilter = function(){
			var nInfo = document.createElement( 'div' );
			var filterStr  = '<div>'+
					            '<span class="filter-label">渠道分组：</span>'+
				                '<div class="filter-item" id="product-customerGroup-box">'+
			                	'<span class="ui-combo-wrap customerGroup">'+
								'	<input type="text" class="input-txt name customerGroupName" readonly="readonly">'+
								'	<input type="hidden" class="cur-id" value="" />'+
								'	<i class="trigger"></i>'+
								'</span>'+
							  '</div>';
			$(nInfo).append(filterStr);
			return nInfo;
		};
		
		/**
		 * 设置从服务器端获取数据的方法
		 */
		var retrieveCusData = function(sSource, aoData, fnCallback,oSettings) {
			var iLength = $('#'+seinorid).dataTable().fnPagingInfo().iLength;
			var iPage   = $('#'+seinorid).dataTable().fnPagingInfo().iPage;
			var iSearch = $('#'+seinorid+'_wrapper .dataTables_filter input').val();
			var sEcho = fnGetKey(aoData, "sEcho");
			var callServer = fnGetKey(aoData, "callServer")==null?true: fnGetKey(aoData, "callServer");
			var sortColumn = getSortTitle(oSettings,aoData);
			var sortDire = getSortDire(oSettings);		
			var customergroupid = $(".customerGroup").find('.cur-id').val();
			$('#'+seinorid+' .group-checkable').prop("checked",false);
			ajax.call(sSource, {
						start: iPage * iLength, 
						limit: iLength,
						sEcho :sEcho, 
						queryParam:iSearch,
						sortColumn:sortColumn,
						sortDire :sortDire,
						customergroupid:customergroupid,
						departmentid:$("#depart-id").val(),
								},
					function(datas, status) {
						$('#'+seinorid+' thead tr th span').removeClass("checked");
						fnCallback(datas);
					}
				);
		};
		
		var extend_Cus_Filter = function (){
			var nInfo = document.createElement( 'div' );
			var filterStr  = '<div>'+
								'<span class="filter-label filter-margin">所属销售部门：</span>'+
							    '<div class="filter-item" id="product-type-box">'+
							    	'<span class="ui-combo-wrap" id="departType">'+
										'<input type="text" name="departTypeName" class="input-txt name" readonly="readonly">'+
										'<input type="hidden" id="depart-id" value="" />'+
										'<i class="trigger"></i>'+
									'</span>'+
							    '</div>'+
							  '</div>';
			$(nInfo).append(filterStr);
			return nInfo;
		};
		
		var handleDepartType = function() {
			$(".customerGroup").typeTreeCombo({
				curId: '',
				url: "./customerGroup.do?reqCode=queryCustomerGroupTree",
				width: 150,
				isOnlyLeaf: false,
				valueType: "data-typenumber",
				callback: {
					nameClick: function(a){
						if (isHandledGroupTable) {
							$("#"+seinorid).dataTable().fnDraw();
						}
						isHandledGroupTable = true;
					},
					complete:function(){
						var allItem = '<div class="item parent_0 customerGroupparent_0" style="">'
									+	'<a class="name" href="javascript:void(0)">全部渠道分组</a>'
									+	'<input type="hidden" class="type-id" value="" autocomplete="off">'
									+'</div>';
						$(allItem).prependTo($(".customerGroup").next().find(".type-info"));
						$(".customerGroupparent_0").trigger("click");
					}
				}
			});
		};	
	    return {
	        init: function (url,id) {
	        	seinorid = id;
	        	seinorurl = url;
	            selectCustomerTable();
	            handleDepartType();
	        }
	    };
	}();
	
	this.manageCustomergroup= function(){
		var dataurl,tableid;
		var selectTable = function() {
			if(!jQuery().dataTable){
				return ;
			}
	        // begin  table
	        $('#'+tableid).dataTable({
	            "bProcessing": true,                     //加载数据时显示正在加载信息  
	            "bServerSide": true,                     //指定从服务器端获取数据  
	            "sAjaxSource": dataurl,//获取数据的url  
	            "fnServerData": retrieveData,           //获取数据的处理函数  
	            "bAutoWidth": true,                    //自适应宽度
	            "bFilter" : true,                       // 搜索栏
	            "ajax" : "load",
	            "fnQueryTip" : "请输入渠道分组名称/编码",
	            "aoColumns" : [
	             {
	        		"mData" : null,
	        		"sTitle" : null,
	        		'bSortable': false,
	        		"sDefaultContent" : "",
	            	"mRender" : function(data, type, row) {
	        			return "<div class='checker'><span>" +
	        					"<input type='checkbox'  class='checkboxes' id='selectedData' value='1'/>"+
	        					"</span></div>";
	        		}   
	        	},{
	        		"mData" : 'number',
	        		"sTitle" : "渠道分组编码",
	        		"bSortable" : true
	        	},{
	        		"mData" : 'name',
	        		"sTitle" : "渠道分组名称",
	        		"bSortable" : true,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='name'>"+data+"</span>";
	        		}  
	        	},{
	        		"mData" : 'id',    
	        		"sTitle" : "渠道分组内码",
	        		"sClass":"hideColumn",
	        		"bSortable" : false,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='id'>"+data+"</span>";
	        		}  
	        	}
	        	],
	           
	        });
	        jQuery('#'+tableid+'_wrapper .dataTables_filter input').addClass("form-control"); // modify table search input
			
	        jQuery('#'+tableid+' .group-checkable').change(function (event) {
	            var set = jQuery(this).attr("data-set");
	            var checked = jQuery(this).is(":checked");
	            $(this).closest('span').toggleClass("checked");
	           	jQuery(set).each(function () {
	                if (checked) {
	                    $(this).attr("checked", true);
	                    $(this).closest('span').addClass("checked");
	                    $(this).closest('tr').addClass("active");
	                } else {
	                    $(this).attr("checked", false);
	                    $(this).closest('span').removeClass("checked");
	                    $(this).closest('tr').removeClass("active");
	                }
	            });
	            jQuery.uniform.update(set);
	        });
	        
	        //单击事件监听
	        $('#'+tableid+' tbody tr').live('click', function () {
	        	var nTds = $('td', this);
	        	var set = nTds[0].children[0].children[0].children[0];
	        	var checked = $(set).is(":checked");
	        	$('span', this).toggleClass("checked");
	        	$(this).toggleClass("active");
	        	$(set).attr("checked", !checked);
	    	});
	        // 处理关于点击Input 第一列选中框，再次触发单击事件的情况
	    	$("#"+tableid+" tbody tr input").live('click', function(e){
	    		var checked = $(this).is(":checked");
	    		$(this).closest('span').toggleClass("checked");
	    		$(this).closest('tr').toggleClass("active");
		    	e.stopPropagation();
	    	});
		};
		/**
		 * 设置从服务器端获取数据的方法
		 */
		var retrieveData = function(sSource, aoData, fnCallback,oSettings) {
			var iLength = $('#'+tableid).dataTable().fnPagingInfo().iLength;
			var iPage   = $('#'+tableid).dataTable().fnPagingInfo().iPage;
			var iSearch = $('#'+tableid+'_wrapper .dataTables_filter input').val();
			var sEcho = fnGetKey(aoData, "sEcho");
			var callServer = fnGetKey(aoData, "callServer")==null?true: fnGetKey(aoData, "callServer");
			var sortColumn = getSortTitle(oSettings,aoData);
			var sortDire = getSortDire(oSettings);		
			$('#'+tableid+' .group-checkable').prop("checked",false);
			ajax.call(sSource, {
						start: iPage * iLength, 
						limit: iLength,
						sEcho :sEcho, 
						queryParam:iSearch,
						sortColumn:sortColumn,
						sortDire :sortDire,
								},
					function(datas, status) {
						$('#'+tableid+' thead tr th span').removeClass("checked");
						fnCallback(datas);
					}
				);
		};
	    return {
	        init: function (url,id) {
	        	dataurl = url;
	        	tableid = id;
	        	selectTable();
	        }
	    };
	}();
	
	
	this.manageItem= function(){
		var dataurl,tableid;
		var selectTable = function() {
			if(!jQuery().dataTable){
				return ;
			}
	        // begin  table
	        $('#'+tableid).dataTable({
	            "bProcessing": true,                     //加载数据时显示正在加载信息  
	            "bServerSide": true,                     //指定从服务器端获取数据  
	            "sAjaxSource": dataurl,//获取数据的url  
	            "fnServerData": retrieveData,           //获取数据的处理函数  
	            "bAutoWidth": true,                    //自适应宽度
	            "bFilter" : true,                       // 搜索栏
	            "ajax" : "load",
	            "fnQueryTip" : "请输入商品名称/编码/规格型号",
	            "aoColumns" : [
	             {
	        		"mData" : null,
	        		"sTitle" : null,
	        		'bSortable': false,
	        		"sDefaultContent" : "",
	            	"mRender" : function(data, type, row) {
	        			return "<div class='checker'><span>" +
	        					"<input type='checkbox'  class='checkboxes' id='selectedData' value='1'/>"+
	        					"</span></div>";
	        		}   
	        	},{
	        		"mData" : 'number',
	        		"sTitle" : "商品编码",
	        		"bSortable" : true
	        	},{
	        		"mData" : 'name',
	        		"sTitle" : "商品名称",
	        		"bSortable" : true,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='name'>"+data+"</span>";
	        		}  
	        	},{
	        		"mData" : 'specifications',
	        		"sTitle" : "规格型号",
	        		"bSortable" : true,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='name'>"+data+"</span>";
	        		}  
	        	},{
	        		"mData" : 'id',    
	        		"sTitle" : "商品内码",
	        		"sClass":"hideColumn",
	        		"bSortable" : false,
	            	"mRender" : function(data, type, row) {
	        			return "<span id='id'>"+data+"</span>";
	        		}  
	        	}
	        	],
	           
	        });
	        jQuery('#'+tableid+'_wrapper .dataTables_filter input').addClass("form-control"); // modify table search input
			
	        jQuery('#'+tableid+' .group-checkable').change(function (event) {
	            var set = jQuery(this).attr("data-set");
	            var checked = jQuery(this).is(":checked");
	            $(this).closest('span').toggleClass("checked");
	           	jQuery(set).each(function () {
	                if (checked) {
	                    $(this).attr("checked", true);
	                    $(this).closest('span').addClass("checked");
	                    $(this).closest('tr').addClass("active");
	                } else {
	                    $(this).attr("checked", false);
	                    $(this).closest('span').removeClass("checked");
	                    $(this).closest('tr').removeClass("active");
	                }
	            });
	            jQuery.uniform.update(set);
	        });
	        
	        //单击事件监听
	        $('#'+tableid+' tbody tr').live('click', function () {
	        	var nTds = $('td', this);
	        	var set = nTds[0].children[0].children[0].children[0];
	        	var checked = $(set).is(":checked");
	        	$('span', this).toggleClass("checked");
	        	$(this).toggleClass("active");
	        	$(set).attr("checked", !checked);
	    	});
	        // 处理关于点击Input 第一列选中框，再次触发单击事件的情况
	    	$("#"+tableid+" tbody tr input").live('click', function(e){
	    		var checked = $(this).is(":checked");
	    		$(this).closest('span').toggleClass("checked");
	    		$(this).closest('tr').toggleClass("active");
		    	e.stopPropagation();
	    	});
		};
		/**
		 * 设置从服务器端获取数据的方法
		 */
		var retrieveData = function(sSource, aoData, fnCallback,oSettings) {
			var iLength = $('#'+tableid).dataTable().fnPagingInfo().iLength;
			var iPage   = $('#'+tableid).dataTable().fnPagingInfo().iPage;
			var iSearch = $('#'+tableid+'_wrapper .dataTables_filter input').val();
			var sEcho = fnGetKey(aoData, "sEcho");
			var callServer = fnGetKey(aoData, "callServer")==null?true: fnGetKey(aoData, "callServer");
			var sortColumn = getSortTitle(oSettings,aoData);
			var sortDire = getSortDire(oSettings);		
			$('#'+tableid+' .group-checkable').prop("checked",false);
			ajax.call(sSource, {
						start: iPage * iLength, 
						limit: iLength,
						sEcho :sEcho, 
						queryParam:iSearch,
						sortColumn:sortColumn,
						sortDire :sortDire,
								},
					function(datas, status) {
						$('#'+tableid+' thead tr th span').removeClass("checked");
						fnCallback(datas);
					}
				);
		};
	    return {
	        init: function (url,id) {
	        	dataurl = url;
	        	tableid = id;
	        	selectTable();
	        }
	    };
	}();
	
	this.getRemoteSelectedMulti = function(inputid,tableid) {
		//检查是否有被勾选的数据
		var set = jQuery(jQuery('#'+tableid+' .group-checkable')[0]).attr("data-set");
	    var index = 0;
		var count =0;
	    jQuery(set).each(function () {
	        if(jQuery(this).is(":checked")){
	        	count++;
	        }
	    });
	    var list = [];
	    if(count > 0){
	    	var idlist = $("#"+inputid).val().split(",");
	    	var tbody$ = $('#'+tableid+' tbody')[0];
		    jQuery(set).each( function() {
				if (jQuery(this).is(":checked")) {
					seinfo =  new seInfo();
					seinfo.id = $($(tbody$.children[index]).find("span[id='id']")).html();
					seinfo.name =$($(tbody$.children[index]).find("span[id='name']")).html();
					if(idlist.indexOf(seinfo.id) == -1){
						list.push(seinfo);
					}
				}
				index++;
			});
	    }
	    return list;
	};
	
	this.clearSingleSelected = function(id) {
		$("#"+id).val("");
		var ul = $("#"+id).closest("div").find("ul");
		$(ul).find("li[class='select2-search-choice']").each(function (){
			this.remove();
		});	
	};
	
	this.clearSingleInput = function(id) {
		$("#"+id).val("");
	};
}
